﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartCollector.Domain.Entity;
using System.Data.Linq;
using SmartCollector.Domain.Exceptions;

namespace SmartCollector.Domain.Repository
{
    public class CategoryRepository
    {
        private Table<tbl_Category> m_categories;
        public IQueryable<tbl_Category> Categories
        {
            get
            {
                return m_categories.AsQueryable();
            }
        }
        public CategoryRepository()
        {
            m_categories = (new EntityDomainDataContext()).GetTable<tbl_Category>();
        }

        public void AddNewCategory(string categoryName, bool isActive)
        {
            var item = m_categories.Where(c => c.CategoryName == categoryName).FirstOrDefault();
            if (item != null)
            {
                throw new CategoryAlreadyExistException(categoryName, item.ID);
            }
            m_categories.InsertOnSubmit(
                new tbl_Category
                {
                    CategoryName = categoryName,
                    Active = isActive
                });
        }

        public void AddNewCategory(string categoryName, bool isActive,int parentId)
        {
            var item = m_categories.Where(c => c.CategoryName == categoryName).FirstOrDefault();
            if (item != null)
            {
                throw new CategoryAlreadyExistException(categoryName, item.ID);
            }
            m_categories.InsertOnSubmit(
                new tbl_Category
                {
                    CategoryName = categoryName,
                    Active = isActive,
                    ParentID = parentId
                });
        }

        public void AddNewCategory(tbl_Category categoryItem)
        {
            var item = m_categories.Where(c => c.CategoryName == categoryItem.CategoryName).FirstOrDefault();
            if (item != null)
            {
                throw new CategoryAlreadyExistException(item.CategoryName, item.ID);
            }
            m_categories.InsertOnSubmit(categoryItem);
        }

        public void RemoveCategory(tbl_Category category)
        {
            m_categories.DeleteOnSubmit(category);
        }

        public void RemoveCategory(int categoryId)
        {
            tbl_Category selectedCategory = m_categories.Where(p => p.ID == categoryId).First();
            if (selectedCategory != null)
            {
                RemoveCategory(selectedCategory);
            }
        }

        public void SubmitChanged()
        {
            m_categories.Context.SubmitChanges();
        }
    }
}
